package enhanced.neural.network.convert;

import cn.hutool.core.date.DateUtil;
import org.apache.ibatis.type.*;

import java.sql.*;
import java.text.SimpleDateFormat;

public class DateTypeHandler extends BaseTypeHandler<String> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        // 这里根据需求进行日期格式化操作，然后设置到PreparedStatement中
        try {
            ps.setTimestamp(i, Timestamp.valueOf(DateUtil.parseDateTime(parameter).toLocalDateTime()));
        } catch (Exception e) {
            throw new RuntimeException("Failed to parse date string.");
        }
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        // 从结果集中获取日期值，并按照需求进行格式化返回
        return formatDateToString(rs.getTimestamp(columnName));
    }

    /**
     * @param rs
     * @param columnIndex
     * @return
     * @throws SQLException
     */
    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Timestamp sqlTimestamp = rs.getTimestamp(columnIndex);
        return sqlTimestamp != null ? formatDateToString(sqlTimestamp) : null;
    }

    /**
     * @param cs
     * @param columnIndex
     * @return
     * @throws SQLException
     */
    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Timestamp sqlTimestamp = cs.getTimestamp(columnIndex);
        return sqlTimestamp != null ? formatDateToString(sqlTimestamp) : null;
    }

    private String formatDateToString(Timestamp timestamp) {
        if (timestamp == null) {
            return "";
        }
        return DateUtil.formatDateTime(DateUtil.date(timestamp.getTime()));
    }
}
